<?php
	if(!session_id()) { @session_start(); }
    $root = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))));	
	if (file_exists($root.'/wp-load.php')) {
		require_once($root.'/wp-load.php');	
	}		
	
	if($_SERVER['REQUEST_METHOD'] === 'POST'){
		$_SESSION['paypal_post_session'] = json_encode($_POST);
	}
	
	$plugin_url = plugins_url('',  dirname(__FILE__));
	$base =   dirname(dirname(dirname(__FILE__)));

	require_once($base.'/objects/class_pyapal_express_checkout.php');
	
	$api_username = urlencode(get_option('moveto_paypal_api_username'));
	$api_password = urlencode(get_option('moveto_paypal_api_password'));
	$api_signature = urlencode(get_option('moveto_paypal_api_signature'));
	$paypaltestmode = get_option('moveto_paypal_testing_mode');
	
	$guest_payment_st = get_option('moveto_paypal_guest_checkout');

	$version = urlencode('109.0');
	$pp_return_url = urlencode($plugin_url.'/lib/paypal_payment_process.php');
	$pp_cancel_url = urlencode(site_url());
	$currency_code = get_option('moveto_currency');
	$payment_action = urlencode("SALE");
	$locale_code = 'US';
	
	$site_logo='';
	
	$border_color = '2285C6';
	$allow_note = 1;
	$p = new mp_paypal();
	
	if($paypaltestmode=='D'){
		$p->mode = '';
	}else{
		$p->mode = 'SANDBOX';
	}
	
	/*set basic name and value pairs for curl post*/
	$basic_NVP = array(
					'VERSION'=>$version,
					'USER'=>$api_username,
					'PWD'=>$api_password,
					'SIGNATURE'=>$api_signature,
					'RETURNURL'=>$pp_return_url,
					'CANCELURL'=>$pp_cancel_url,
					'PAYMENTREQUEST_0_CURRENCYCODE'=>$currency_code,
					'NOSHIPPING'=>1,
					'PAYMENTREQUEST_0_PAYMENTACTION'=>$payment_action,
					'LOCALECODE'=>$locale_code,
					'CARTBORDERCOLOR'=>$border_color,
					'LOGOIMG'=>$site_logo,
					'ALLOWNOTE'=>1
				);  
	if($guest_payment_st=='E'){
		$basic_NVP['SOLUTIONTYPE']='Sole';
		$basic_NVP['LANDINGPAGE']='Billing';
	}			
	
	foreach($basic_NVP as $key => $value) {
		$p->pv .= "&$key=$value";
	}
	
		$subtotal = $_SESSION['final_amt'] - $_SESSION['tax'];
		$cart_item_counter=0;	
		/* $p->pv .= "&L_PAYMENTREQUEST_0_NAME$cart_item_counter=$service_title"; */
		$p->pv .= "&L_PAYMENTREQUEST_0_DESC$cart_item_counter=".date_i18n('Y-m-d H:i:s');
		$p->pv .= "&L_PAYMENTREQUEST_0_AMT$cart_item_counter=".$subtotal;
		$p->pv .= "&L_PAYMENTREQUEST_0_QTY$cart_item_counter=1";

		$cart_item_counter++;
		$p->pv .= "&PAYMENTREQUEST_0_ITEMAMT=".$subtotal;	   		   			
		$p->pv .= "&PAYMENTREQUEST_0_TAXAMT=".number_format($_SESSION['tax'],2,".",','); 
		$p->pv .= "&PAYMENTREQUEST_0_AMT=".number_format($_SESSION['final_amt'],2,".",',');
	
	
	$p->pp_method_name = 'SetExpressCheckout';  /*method name using for API call*/
	$resultarray = array();
	
	if(!isset($_GET["token"])) {
		$response_array = $p->paypal_nvp_api_call();
		/*Respond according to message we receive from Paypal*/
		if("SUCCESS" == strtoupper($response_array["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($response_array["ACK"])){
			if(strtoupper($p->mode)=='SANDBOX') {
			  $p->mode = '.sandbox';
			}
			/*Redirect user to PayPal store with Token received.*/
			$paypal_url ='https://www'.$p->mode.'.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token='.$response_array["TOKEN"].'';
			$resultarray['status']='success';
			$resultarray['value']=$paypal_url;
			echo json_encode($resultarray);die();
		}else{
			$resultarray['status']='error';
			$resultarray['value']=urldecode($response_array["L_LONGMESSAGE0"]);
			echo json_encode($resultarray);die();
		}
	}
	
	if(isset($_GET["token"]) && isset($_GET["PayerID"]))
	{
		$token = $_GET["token"];
		$payer_id = $_GET["PayerID"];	
		$p->pv .= "&TOKEN=".urlencode($token)."&PAYERID=".urlencode($payer_id);
		$p->pp_method_name = 'DoExpressCheckoutPayment';  /*method name using for API call*/
		$payment_response_array = $p->paypal_nvp_api_call(); 
		if("SUCCESS" == strtoupper($payment_response_array["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($payment_response_array["ACK"])) 
		{
			$transaction_id = urldecode($payment_response_array["PAYMENTINFO_0_TRANSACTIONID"]);
			$thankyou_url = get_option('moveto_thankyou_page');
				$thankyou_page_url = "";
				if($thankyou_url != '' && $thankyou_url != null){
					$thankyou_page_url = $thankyou_url;
				}else{
					$thankyou_page_url = "../../frontend/mp_thankyou.php";
				}
		   //echo 'Your Transaction ID : '.urldecode($payment_response_array["PAYMENTINFO_0_TRANSACTIONID"]);	
		 
		  ?>
		   <script src="../js/jquery-2.1.4.min.js" type="text/javascript"></script>
		   <script>
		   var dataString = <?php   echo $_SESSION['paypal_post_session']; ?>;
			function checkout_at_booking_complete(trans_id){
				dataString['payment_method'] = "paypal_payment";
				dataString['paypal_transaction_id'] = trans_id;
				jQuery.ajax({
					type:'POST',
					url:'mp_front_ajax.php',
					data: dataString,
					success:function(response){
							window.location.href='<?php echo $thankyou_page_url;?>';
					}
				});
			}
			checkout_at_booking_complete('<?php echo $transaction_id; ?>');
			</script>
			<?php 
		}
	}
?>